<?php
namespace Crm\Domain;

use Carbon\Carbon;
use Crm\Common\Pager as Pager;
use Crm\Common\MetaData as MetaData;

class Score
{
    /**
     * pdo连接。
     *
     * @var object
     * @access pdo
     */
    public $pdo;

    public $metaData;
    public $baseCode;
    public $scoreOption;//积分规则配置
    public $dayOfWeek;//今天是一周的第几天


    public function __construct()
    {
        $this->pdo = \PhalApi\DI()->pdo;
        $this->baseCode = (object)\PhalApi\DI()->config->get('basecode');
        $this->metaData = new MetaData();
        $this->scoreOption = $this->metaData->getPairBaseCodeByType(20203);
        $this->dayOfWeek = Carbon::today()->dayOfWeek;
        //echo Carbon::createFromFormat('Y-m-d H:i:s','2020-03-16 00:00:00')->timestamp;echo '<br>';
        //echo Carbon::createFromFormat('Y-m-d H:i:s','2020-03-16 00:00:00')->addDay(1)->timestamp;exit;
    }

    /* 积分规则. */
    public function rule($mall_id,$data){
        $where = 'flag=1 AND mall_id='.$mall_id;
        if(isset($data['code']) && !empty($data['code'])){
            $where .= " AND code = ".$data['code'];
        }
        if(isset($data['parent_code']) && !empty($data['parent_code'])){
            $where .= " AND parent_code = ".$data['parent_code'];
        }
        if(isset($data['alias']) && !empty($data['alias'])){
            $where .= " AND alias = '".$data['alias']."'";
        }
        $setting = $this->pdo->find(
            DB_PREFIX_MK."mall_setting",
            $where." order by id asc",
            "code, name, value,alias,img_url,rule,des"
        );
        //echo $this->pdo->getLastSql();
        if($data['user_id']!=0) {
            $sql = "select id,mobile from wx_user where id={$data['user_id']}";
            $user = $this->pdo->getRow($sql);
        }
        foreach ($setting as $key=>$item){
            $arr=explode("\n",$item['rule']);
            $str='';
            $pstr='';
            foreach ($arr as $value){
                $str .=$value.'<br>';
                $pstr .='<p>'.$value.'</p>';
            }
            $setting[$key]['rule'] = $str;
            $setting[$key]['prule'] = $pstr;
            $setting[$key]['finish'] = '去完成';
            $setting[$key]['finish_bg'] = 'burlywood';
            $setting[$key]['title_bg'] = 'blue';
            $setting[$key]['btn1'] = '关闭';
            switch($item['code']){
                case '2020301':
                    //签到
                    $setting[$key]['btn1'] = '知道了';
                    break;
                case '2020305':
                    //观看美文
                    $setting[$key]['btn1'] = '知道了';
                    $setting[$key]['btn2'] = '马上参加';
                    break;
                case '2020306':
                    //观看美文
                    $setting[$key]['btn1'] = '知道了';
                    $setting[$key]['btn2'] = '马上参加';
                    break;
                case '2020308':
                    //完善资料
                    if(isset($user['mobile']) && !empty($user['mobile'])) {
                        $setting[$key]['finish'] = '已完成';
                        $setting[$key]['finish_bg'] = 'green-sea';
                        $setting[$key]['btn1'] = '知道了';
                    }
                    break;
                case '2020309':
                    //注册
                    if($user['id']!=0) {
                        $setting[$key]['finish'] = '已完成';
                        $setting[$key]['finish_bg'] = 'green-sea';
                        $setting[$key]['btn1'] = '知道了';
                    }
                    break;
                default:
                    break;
            }
            $setting[$key]['super_value'] = $item['value']*2;
        }
        return $setting;
    }

    /* 积分列表. */
    public function search($data){
        $page_info = "";//url参数
        $orderField = isset($data['sort']) ? $data['sort'] : 'id';//排序字段
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';//排序类型
        $pageSize = isset($data['pageSize']) ? $data['pageSize'] : 15;//分页，每页显示数量
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 1;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;

        $where = 'where 1=1 ';

        //是否有效
        $flag = isset($data['flag'])?$data['flag']:'1';
        if($flag!= ''){
            $where .= " and flag={$flag}";
            $page_info .="flag=".$flag."&";
            $filter['flag'] = $flag;
        }

        //商城ID
        $mall_id = isset($data['mall_id'])?$data['mall_id']:0;
        $where .= " and mall_id={$mall_id}";
        $page_info .="mall_id=".$mall_id."&";
        $filter['mall_id'] = $mall_id;

        //项目信息(del)
        $project_id = isset($data['project_id'])?$data['project_id']:'';
        if($project_id!= '') {
            $where .= " and project_id={$project_id}";
            $page_info .= "project_id=" . $project_id . "&";
            $filter['project_id'] = $project_id;
        }

        //用户id
        $user_id = isset($data['user_id']) ? $data['user_id'] : 0;
        if($user_id!=0) {
            $where .= " and create_uid={$user_id}";
            $page_info .= "user_id=" . $user_id . "&";
            $filter['user_id'] = $user_id;
        }

        //积分消费方式1获取2兑换
        $category = isset($data['category'])?$data['category']:0;
        if($category!= 0){
            $where .= " and category={$category}";
            $page_info .="category=".$category."&";
            $filter['category'] = $category;
        }

        $select_columns = "select %s from wx_user_score %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'ScoreList');
        }else{
            $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            $res[$key]['create_date_val'] = date('Y-m-d',$item['create_date']);
            //todo 后期可以考虑单独制作兑换商品页面
            if($category==2){
                $sql= "select a.status,b.img_url from wx_user_award as a LEFT JOIN mk_mall_award as b on a.award_id=b.id where a.id=".$item['action_id'];
                $ainfo = $this->pdo->getRow($sql);
                $res[$key]['img_url'] = $ainfo['img_url'];
                $res[$key]['status'] = $ainfo['status'];
                $res[$key]['status_val'] = $ainfo['status']==0?'未领取':'已领取';
            }
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 获得用户积分. */
    public function getScore($user_id,$code,$mall_id){
        $sql = "select * from wx_user_score where create_uid={$user_id} and flag=1 and type={$code} and mall_id={$mall_id}";
        $rlt = $this->pdo->getAll($sql);
        return $rlt;
    }

    /* 周签到列表. */
    public function weekSignList($user_id){
        $curWeeks = array();
        $dt = Carbon::create();
        foreach(new \DatePeriod(new \DateTime($dt->startOfWeek()),new \DateInterval('P1D'),new \DateTime($dt->endOfWeek())) as $key=>$d){
            $w = date("w",strtotime($d->format('Y-m-d')));
            $weekarray=array("周日","周一","周二","周三","周四","周五","周六");
            $curWeeks[$key]['date'] = $d->format('Y-m-d');
            $curWeeks[$key]['weekName'] = $weekarray[$w];
            $curWeeks[$key]['isSign'] = 0;
            //if($key==1)$curWeeks[$key]['isSign'] = 1;
        }
        if($user_id>0) {
            //获取本周签到记录
            $sql = "select id,create_date,create_uid,FROM_UNIXTIME(create_date,'%Y-%m-%d') as create_date_val,type,score,`desc` from wx_user_score where create_date>=" . strtotime($dt->startOfWeek()) . " and create_date<" . strtotime($dt->endOfWeek()) . " and create_uid={$user_id} and type=2020301";
            $scores = $this->pdo->getAll($sql);

            foreach ($curWeeks as $key => $item) {
                foreach ($scores as $child) {
                    if ($item['date'] == $child['create_date_val']) $curWeeks[$key]['isSign'] = 1;
                }
            }
        }
        return $curWeeks;
    }

    /* 用户签到. */
    public function sign($user_id,$mall_id=0,$seriesNum,$user_type){
        $isSign = $this->isSign($user_id);
        if(!$isSign){
            $rlt = $this->addScore($user_id,2020301,'wx_user',$user_id,$mall_id,$user_type);
            if($rlt['ret']==200){
                $rlt2 = $this->seriesSign($user_id,$mall_id,$seriesNum);//处理连续签到
                if($rlt2['status']==1 && $rlt2['isSeriesOk']==1){
                    $resutl = array('ret' => '200', 'msg' => '您已经成功签到'.$seriesNum.'天,您已经活动连续签到积分奖励,同时我们会清理您的连续签到次数,重新计算连续签到！','isSeriesOk'=>1);
                }else{
                    $resutl = array('ret' => '200', 'msg' => '签到成功！','isSeriesOk'=>0);
                }
            }else{
                $resutl = array('ret' => '400', 'msg' => '签到失败！');
            }
        }else{
            $resutl = array('ret' => '400', 'msg' => '今日已签到！');
        }
        return $resutl;
    }

    /* 根据日期检查用户是否签到. */
    public function isSign($user_id,$date=''){
        if(empty($date)){
            $today = Carbon::today()->timestamp;
            $tomorrow = Carbon::tomorrow()->timestamp;
        }else{
            $today = Carbon::createFromFormat('Y-m-d H:i:s',$date.' 00:00:00')->timestamp;
            $tomorrow = Carbon::createFromFormat('Y-m-d H:i:s',$date.' 00:00:00')->addDay(1)->timestamp;
        }

        $sql = "select count(*) as cnt from wx_user_score where type=2020301 and create_uid={$user_id} and create_date>=".$today." and create_date<".$tomorrow;
        $rlt = $this->pdo->getRow($sql);
        if($rlt['cnt']>0){
            return true;
        }else{
            return false;
        }
    }

    /* 根据积分类型,添加积分记录. */
    public function addScore($user_id='',$code=0,$action,$action_id=0,$mall_id=0,$user_type=9){
        $code = intval($code);
        if($user_id!='' && $code!=0) {
            $score = $this->scoreByCode($code);
            $data = array(
                'create_date' => time(),
                'create_uid' => $user_id,
                'flag' => 1,
                'mall_id'=>$mall_id,//只要后期需要统计项目所有积分时才有用
                'name' => $score['name'],
                'score' => $score['value'],
                'type' => $score['code'],
                'desc' => $score['desc'],
                'action' => $action,
                'action_id' => $action_id
            );
            //user_type=8为业主,积分翻倍
            //if($user_type==8)$data['score'] = $data['score']*2;
            $rlt = $this->pdo->add($data, 'wx_user_score');
            if($rlt){
                $this->updateUserScore($user_id,$score['value']);
                if($code=='2020306' || $code=='2020305') {
                    //2020306分享,2020305观看
                    $resutl = array('ret' => '200', 'msg' => $score['alias']."+".$data['score']);
                }else{
                    $resutl = array('ret' => '200', 'msg' => '成功获得积分!');
                }
            }else{
                $resutl = array('ret' => '200', 'msg' => '您没有获得积分!');
            }
        }else{
            $resutl = array('ret' => '400', 'msg' => '操作失败!');
        }
        return $resutl;
    }

    /* 更新用户总积分 */
    public function updateUserScore($user_id,$score=0){
        $sql = "update wx_user set score=score+".$score." where id={$user_id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 统计用户总积分. */
    public function countUserScore($user_id){
        //总计获得积分
        $sql = "select sum(score) as num from wx_user_score where create_uid={$user_id} and category=1 and flag=1";
        $obtain = $this->pdo->getRow($sql);
        //兑换积分
        $sql = "select sum(score) as num from wx_user_score where create_uid={$user_id} and category=2 and flag=1";
        $consume = $this->pdo->getRow($sql);

        $cnt['obtain'] = empty($obtain['num'])?0:$obtain['num'];
        $cnt['consume'] = empty($consume['num'])?0:$consume['num'];
        $cnt['surplus'] = $obtain['num']-$consume['num'];
        //计算用等级
        if($cnt['obtain']<=100){
            $cnt['level'] = 'Lv1.0';
            $cnt['level_color'] = 'blue';
        }elseif ($cnt['obtain']>100 || $cnt['obtain']<=300){
            $cnt['level'] = 'Lv2.0';
            $cnt['level_color'] = 'darkgreen';
        }elseif ($cnt['obtain']>300 || $cnt['obtain']<=500){
            $cnt['level'] = 'Lv3.0';
            $cnt['level_color'] = 'darkcyan';
        }elseif ($cnt['obtain']>500 || $cnt['obtain']<=100){
            $cnt['level'] = 'Lv4.0';
            $cnt['level_color'] = 'orange';
        }elseif ($cnt['obtain']>1000 || $cnt['obtain']<=2000){
            $cnt['level'] = 'Lv5.0';
            $cnt['level_color'] = 'purple';
        }else{
            $cnt['level'] = 'Lv5.0';
            $cnt['level_color'] = 'purple';
        }
        return $cnt;
    }

    /********************** 积分签到 *************************/
    /* 连续签到 [规则] */
    public function seriesSign($user_id,$mall_id,$seriesNum,$user_type=9){
        //获取前一天时间,判断是否有前一天签到
        $isYestodaySign = $this->isYestodaySign($user_id);
        if($isYestodaySign){
            //连续签到
            $this->pdo->doSql("update wx_user set series_sign_num=series_sign_num+1 where id={$user_id}");
            //判断是否连续签到30天
            $user = $this->pdo->getRow("select series_sign_num from wx_user where id={$user_id}");
            $rlt = array('status'=>1,'isSeriesOk'=>0);
            if($user['series_sign_num']%$seriesNum==0){
                //连续签到30次,则获得愚公移山奖励
                $this->addScore($user_id,2020304,'wx_user',$user_id,$mall_id,$user_type);
                $rlt = array('status'=>1,'isSeriesOk'=>1);
            }
        }else{
            //不是连续签到,清除wx_user表中连续签到series_sign_num数量改为1
            $this->pdo->doSql("update wx_user set series_sign_num=1 where id={$user_id}");
            $rlt = array('status'=>0,'isSeriesOk'=>0);
        }
        return $rlt;
    }

    /* 监测客户前一天是否签到 */
    public function isYestodaySign($user_id){
        //获取前一天时间,判断是否有前一天签到
        $today = Carbon::today()->timestamp;
        $yestoday = Carbon::yesterday()->timestamp;
        $sql = "select count(*) as cnt from wx_user_score where type=2020301 and create_uid={$user_id} and create_date>=".$yestoday." and create_date<".$today;
        $rlt = $this->pdo->getRow($sql);
        if($rlt['cnt']>0){
            return true;
        }else{
            return false;
        }
    }

    /* 设置签到次数 */
    public function setSignNum($user_id,$num=0){
        $rlt = $this->pdo->doSql("update wx_user set series_sign_num=".$num." where id={$user_id}");
        return $rlt;
    }

    /**
     * 根据积分类型,检查是否获得该积分
     * 通过积分获得规则进行判断
     * @param $user_id string 被检测用户
     * @param $code string  2020301签到,2020302邀请好友,2020303推荐好友,2020304愚公移山,2020305观看美文,到2020306分享美文,2020307参加活动,2020308完善资料,2020309注册,2020310邀请参与活动,2020311分享楼盘
     * @param $action string 表主体名称(用户wx_user,文章cms_contentindex,项目fc_project等
     * @param $action_id int 主体ID
     * @param $mall_id int 商城ID
     * @param $date string 积分获得时间,默认当天
     * @return $rlt boolean 检测结果
     */
    public function checkObtainScore($user_id,$code,$action,$action_id=0,$mall_id,$date){
        if(empty($date)){
            $today = Carbon::today()->timestamp;
            $tomorrow = Carbon::tomorrow()->timestamp;
        }else{
            $today = Carbon::createFromFormat('Y-m-d H:i:s',$date.' 00:00:00')->timestamp;
            $tomorrow = Carbon::createFromFormat('Y-m-d H:i:s',$date.' 00:00:00')->addDay(1)->timestamp;
        }
        $where = " type={$code} and mall_id={$mall_id} and action='{$action}' and action_id={$action_id} and create_uid={$user_id}";
        if($code=='2020301'){
            //签到 需要时间验证
            $where .= " and create_date>=" . $today . " and create_date<" . $tomorrow;
        }
        $sql = "select count(*) as cnt from wx_user_score where ".$where;
        $rlt = $this->pdo->getRow($sql);
        if($rlt['cnt']>0){
            return false;
        }else{
            return true;
        }
    }

    /* 验证得分规则 */
    public function checkObtainRule($user_id,$code,$action,$action_id,$mall_id,$date){
        if(empty($date)){
            $today = Carbon::today()->timestamp;
            $tomorrow = Carbon::tomorrow()->timestamp;
        }else{
            $today = Carbon::createFromFormat('Y-m-d H:i:s',$date.' 00:00:00')->timestamp;
            $tomorrow = Carbon::createFromFormat('Y-m-d H:i:s',$date.' 00:00:00')->addDay(1)->timestamp;
        }
        //验证每日获得阅读、或分享的次数
        if($code=='2020305' || $code=='2020306'){
            $mall = new Mall();
            $config = $mall->config($mall_id);
            //阅读、分享积分需要时间验证(没有又获得积分次数限制)
            $where = " type={$code} and mall_id={$mall_id} and action='{$action}' and create_uid={$user_id} 
                        and create_date>=" . $today . " and create_date<" . $tomorrow;
            $sql = "select count(*) as cnt from wx_user_score where ".$where;
            $rlt = $this->pdo->getRow($sql);
            switch ($code){
                case 2020305:
                    $ruleTimes = $config['setting']['dayReadTimes'];
                    break;
                case 2020306:
                    $ruleTimes = $config['setting']['dayShareTimes'];
                    break;
                default:
                    $ruleTimes = 1;//默认都是1次
                    break;
            }
            if($rlt['cnt']<$ruleTimes){
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }
    }

    /**
     * 判断是否获得过邀请好友积分
     */
    public function checkRecommendScore($user_id,$code,$fuser_id){
        $sql = "select count(*) as cnt from wx_user_score where type={$code} and create_uid={$user_id} and action_id={$fuser_id}";
        $rlt = $this->pdo->getRow($sql);
        if($rlt['cnt']>0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 搜索用户列表
     */
    public function searchWxUser_Del($data){
        $page_info = "";//url参数
        $orderField = isset($data['sort']) ? $data['sort'] : 'id';//排序字段
        $orderValue = isset($data['sort_value']) ? $data['sort_value'] : 'desc';//排序类型
        $pageSize = isset($data['pageSize']) ? $data['pageSize'] : 15;//分页，每页显示数量
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 1;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;

        $where = 'where 1=1 ';

        //推进朋友
        $fuser_id = isset($data['fuser_id'])?$data['fuser_id']:'0';
        if($fuser_id!= ''){
            $where .= " and fuser_id={$fuser_id}";
            $page_info .="fuser_id=".$fuser_id."&";
            $filter['fuser_id'] = $fuser_id;
        }

        $select_columns = "select %s from wx_user %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        if($data['request_type']=='ajax'){
            $page=new pager_page($pageSize,$recordCount,$currentPage,$subPages,$page_info,7,'ScoreConvert');
        }else{
            $page=new pager_page($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        }
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key=>$item){
            $res[$key]['create_date_val'] = date('Y-m-d',$item['create_date']);
        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;
        $result['pageStr'] = $splitPageStr;
        $result['next_page'] = $currentPage;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /**
     * 统计用户的签到、美文转发数量
     */
    public function userActionNum($data){
        $user_id = isset($data['user_id'])?$data['user_id']:0;
        if($user_id!= 0) {
            $where = "where create_uid={$user_id}";

            //项目信息
            $project_id = isset($data['project_id'])?$data['project_id']:'0';
            $where .= " and project_id={$project_id}";

            //开始时间
            $start_date = isset($data['start_date']) ? $data['start_date'] : 0;
            if ($start_date != 0) {
                $where .= " and create_date >= " . $start_date;
            }
            //结束时间
            $end_date = isset($data['end_date']) ? $data['end_date'] : 0;
            if ($end_date != 0) {
                $where .= " and create_date <= " . $end_date;
            }

            $sql_sign = "select count(*) as cnt from wx_user_score " . $where . " and type=2020301";//签到
            $sql_show = "select count(*) as cnt from wx_user_score " . $where . " and type=2020305";//观看美文
            $sql_share = "select count(*) as cnt from wx_user_score " . $where . " and type=2020306";//分享美文
            $num = $this->pdo->getRow($sql_sign);
            $rlt['sign_num'] = $num['cnt'];
            $num = $this->pdo->getRow($sql_show);
            $rlt['show_num'] = $num['cnt'];
            $num = $this->pdo->getRow($sql_share);
            $rlt['share_num'] = $num['cnt'];
            return $rlt;
        }else{
            return false;
        }
    }

    /**
     * 根据code获取积分配置
     */
    public function scoreByCode($code)
    {
        $info = $this->pdo->find(DB_PREFIX_MK.'mall_setting','flag = 1 and code = '.$code,'code,name,alias,value');
        return $info[0];
    }

    /**************** 现场扫码 *****************/
    /**
     * 扫码签到
     */
    public function scanSign($user_id,$mall_id,$project_id,$f_uid,$user_type=9){
        $score = $this->scoreByCode(2020312);
        $data = array(
            'create_date' => time(),
            'create_uid' => $user_id,
            'flag' => 0,//默认为无效,现场停留60分钟,即可生效
            'mall_id'=>$mall_id,//只要后期需要统计项目所有积分时才有用
            'name' => $score['name'],
            'score' => $score['value'],
            'type' => $score['code'],
            'desc' => $score['desc'],
            'action' => 'fc_project',
            'action_id' => $project_id,//现场扫墓签到项目
            'f_uid'=>$f_uid
        );
        //user_type=8为业主,积分翻倍
        //if($user_type==8)$data['score'] = $data['score']*2;
        $rlt = $this->pdo->add($data, 'wx_user_score');
        if($rlt){
            $this->updateUserScore($user_id,$data['score']);
            $result = array('ret' => '200', 'msg' => '签到成功!');
        }else{
            $result = array('ret' => '200', 'msg' => '签到失败!');
        }
        return $result;
    }

    /* 根据日期获取用户是否现场签到记录. */
    public function scanSignInfo($user_id,$date=''){
        if(empty($date)){
            $today = Carbon::today()->timestamp;
            $tomorrow = Carbon::tomorrow()->timestamp;
        }else{
            $today = Carbon::createFromFormat('Y-m-d H:i:s',$date.' 00:00:00')->timestamp;
            $tomorrow = Carbon::createFromFormat('Y-m-d H:i:s',$date.' 00:00:00')->addDay(1)->timestamp;
        }
        $sql = "select id,create_date,create_uid,name,f_uid,mall_id,action,action_id,type,score from wx_user_score where type=2020312 and create_uid={$user_id} and create_date>=".$today." and create_date<".$tomorrow;
        $rlt = $this->pdo->getRow($sql);
        return $rlt;
    }

    /* 用户积分Flag状态更新 */
    public function scoreFlagUpdate($user_id,$score_id,$flag){
        $rlt = $this->pdo->doSql("update wx_user_score set flag=".$flag." where id={$score_id}");
        return $rlt;
    }

    /***************** 积分消费 ****************/
    /* 积分消费 */
    public function consume($user_id,$mall_id=0,$shop_id=0,$score_num=0){
        if($user_id!='' && $mall_id!=0 && $shop_id!=0 && $score_num!=0) {
            $shop = new Shop();
            $shopInfo = $shop->owner($shop_id,$mall_id);
            if(!isset($shopInfo['user_id'])){
                $resutl = array('status' => '200', 'msg' => '很抱歉,支付失败,该商家未绑定!');
                return $resutl;
            }
            $Score = new Score();
            $score = $Score->countUserScore($user_id);
            if($score['surplus']>=$score_num) {
                //记录消费积分
                $data = array(
                    'create_date' => time(),
                    'create_uid' => $user_id,
                    'flag' => 1,
                    'mall_id' => $mall_id,//只要后期需要统计项目所有积分时才有用
                    'name' => $shopInfo['shop_name'],
                    'score' => $score_num,
                    'type' => $shopInfo['shop_id'],//此处存储商家ID
                    'category' => 2,
                    'desc' => '支付商家积分',
                    'action' => 'shop',
                    'action_id' => $shopInfo['shop_id']
                );
                $rlt = $this->pdo->add($data, 'wx_user_score');

                if ($rlt) {
                    $resutl = array('status' => '200', 'msg' => '恭喜您,支付积分成功!');
                } else {
                    $resutl = array('status' => '201', 'msg' => '很抱歉,支付积分失败');
                }
            }else{
                $resutl = array('restatust' => '202', 'msg' => '很抱歉,您的积分不够!');
            }
        }else{
            $resutl = array('status' => '400', 'msg' => '操作失败！');
        }
        return $resutl;
    }

}

